<template>
  <!-- 骑手接单 -->
  <div class="rider-order">
    <Return />
    <div class="rider-order-header" :style="{ height: headerHeight + 'px' }">
      <div class="rider-order-header-bottom">
        <template v-for="(item, index) in riderOrderTabs" :key="item.title">
          <div class="rider-order-header-bottom-item">
            <div class="item-box" :class="{ 'item-box-active': index === activeIndex }" @click="handleTabChange(index)">
              <div>{{ item.title }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <scroll-view class="rider-order-content" scroll-y="true" :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore" @refresherrefresh="onRefresh" :refresher-enabled="true"
      :refresher-triggered="refreshing">
      <div v-if="loading && orderList.length === 0" class="loading-container">
        <div class="loading">加载中...</div>
      </div>

      <div v-else-if="orderList.length === 0" class="empty-container">
        <div class="empty-text">暂无订单</div>
      </div>

      <template v-else>
        <div @click="viewOrderDetail(order)" v-for="(order, orderIndex) in orderList" :key="order.id" class="order-item">
          <!-- 顶部信息栏 -->
          <div class="order-top">
            <div class="shop-info">
              <div class="shop-avatar">
                <img :src="order.storeAvatar || '../static/imgs/banner.png'" alt="">
              </div>
              <div class="shop-detail">
                <div class="shop-name">{{ order.storeName }}</div>
                <div class="order-time">{{ order.createTime }}</div>
              </div>
            </div>
            <div class="order-status">
              <div class="status-badge" :class="getStatusClass(order.status)">
                {{ getStatusText(order.status) }}
              </div>
              <div class="order-amount">¥{{ order.customerDistributionFeeStr }}</div>
            </div>
          </div>

          <span style="display: none;">{{ countdownState }}</span>
          <!-- 订单详情 -->
          <div class="order-detail">
            <div class="goods-summary">
              <span v-if="activeIndex !== 0 && order.singleNumber" class="pickup-code">
                取餐码: {{ order.singleNumber }}
              </span>
              <span v-if="activeIndex !== 0 && order.deliveryFeeStr" class="pickup-code">
                配送费¥: {{ order.deliveryFeeStr }}
              </span>
            </div>

            <!-- 取餐倒计时 -->
            <div v-if="order.status === '2' && order.responseTime" class="delivery-countdown">
              <span class="countdown-icon">⏰</span>
              <span class="countdown-text">取餐倒计时：{{ getPickupCountdown(order.responseTime) }}</span>
            </div>

            <!-- 送餐倒计时 -->
            <div v-if="order.status === '3' && order.distributionTime" class="delivery-countdown">
              <span class="countdown-icon">⏰</span>
              <span class="countdown-text">送餐倒计时：{{ getDeliveryCountdown(order.distributionTime) }}</span>
            </div>

            <!-- 地址信息 -->
            <div class="address-info">
              <div class="address-item">
                <div class="address-tag pickup-tag">取</div>
                <div class="address-text">{{ order.storeAddress }}</div>
              </div>
              <div class="address-item">
                <div class="address-tag delivery-tag">送</div>
                <div class="address-text">{{ order.customerAddress }}</div>
              </div>
            </div>

            <!-- 买家备注 -->
            <div v-if="order.buyerNotes" class="buyer-notes">
              <div class="notes-label">📝 备注：</div>
              <div class="notes-content">{{ order.buyerNotes }}</div>
            </div>
          </div>

          <!-- 底部操作区 -->
          <div class="order-footer">
            <div class="contact-phone" v-if="order.customerPhone">
              <span class="phone-icon">📞</span>
              <span class="phone-number">{{ order.customerPhone }}</span>
            </div>
            <div class="action-btns">
              <button v-if="['0', '1'].includes(order.status)" class="action-btn primary-btn" @click.stop="takeOrder(order)">
                接单
              </button>
              <button v-if="order.status === '2'" class="action-btn primary-btn" @click.stop="startDelivery(order)">
                取餐
              </button>
              <template v-if="order.status === '3'">
                <button class="action-btn secondary-btn" @click.stop="contactCustomer(order)">
                  联系顾客
                </button>
                <button class="action-btn primary-btn" @click.stop="confirmDelivery(order)">
                  送达
                </button>
              </template>
            </div>
          </div>
        </div>
      </template>

      <div v-if="loadingMore" class="loading-more">
        <div class="loading-text">加载更多...</div>
      </div>
    </scroll-view>
  </div>

  <!-- 拍照和备注弹窗保持不变 -->
  <wd-popup v-model="showPhotoDialog" position="center">
    <view class="photo-dialog">
      <view class="dialog-title">
        {{ currentOrderAction === 'pickup' ? '取货凭证' : '送达凭证' }}
      </view>
      <view class="photo-area">
        <view class="photo-list">
          <view v-for="(photo, index) in photoList" :key="index" class="photo-item">
            <image :src="photo.serverUrl || photo.localPath" mode="aspectFill" />
          </view>
          <view class="photo-add" @click="handleTakePhoto" v-if="photoList.length < 3">
            <text class="iconfont icon-camera"></text>
            <text>拍照</text>
          </view>
        </view>
      </view>

      <view class="remarks-area">
        <textarea v-model="remarks" placeholder="请输入备注信息" class="remarks-input" />
      </view>

      <view class="dialog-footer">
        <button @click="showPhotoDialog = false" class="btn-cancel">取消</button>
        <button @click="submitPhotoAndRemarks" class="btn-submit">确定</button>
      </view>
    </view>
  </wd-popup>
</template>

<script setup>
import { baseUrl } from '@/utils/config'
// 获取用户数据
import { useLoginStore } from '@/stores/login'
const loginStore = useLoginStore()
import { ref, onMounted, computed, watch, onUnmounted, nextTick } from 'vue'
import Return from '@/components/Return.vue'

const headerHeight = ref(110) // 设置一个默认值
const contentHeight = ref(600) // 设置一个默认值
const activeIndex = ref(0)
const orderList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const refreshing = ref(false)
const page = ref(1)
const hasMore = ref(true)

// 新增照片和备注相关的状态
const showPhotoDialog = ref(false)
const currentOrderAction = ref(null)
const currentOrder = ref(null)
const photoList = ref([])
const remarks = ref('')

// 添加响应式的倒计时状态
const countdownState = ref(0)

// 添加倒计时相关的状态
const countdownTimers = ref(new Map())
const deliveryCountdownTimers = ref(new Map())

// 添加超时标记，防止重复刷新
const timeoutOrders = ref(new Set())

// 状态文本映射
const statusTextMap = {
  '0': '商家待接单',
  '1': '商家已接单',
  '2': '商家出餐-待配送',
  '3': '骑手已取餐-配送中',
  '4': '骑手配送完成-已完成',
  '5': '待评价',
  '6': '取消',
  '7': '退款中',
  '8': '退款完成',
  '9': '订单已取消',
}

// 修改标签页配置和状态映射
const riderOrderTabs = ref([
  { title: '可接订单', status: '0', type: 'available' },
  { title: '已接单', status: '2', type: 'my' },
  { title: '配送中', status: '3', type: 'my' },
  { title: '已完成', status: '4', type: 'my' }
])

// 计算当前状态
const currentStatus = computed(() => {
  return riderOrderTabs.value[activeIndex.value]?.status || 'waiting'
})

// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    '0': 'status-waiting',
    '1': 'status-accepted',
    '2': 'status-accepted',
    '3': 'status-delivering',
    '4': 'status-completed',
    '5': 'status-completed',
    '6': 'status-cancelled',
    '7': 'status-refunding',
    '8': 'status-refunded'
  }
  return classMap[status] || 'status-default'
}

// 获取取餐倒计时
const getPickupCountdown = (responseTime) => {
  if (!responseTime) return ''

  const now = new Date().getTime()
  const responseTimeStamp = new Date(responseTime).getTime()

  // 设置20分钟倒计时
  const countdownDuration = 20 * 60 * 1000 // 20分钟转换为毫秒
  const endTime = responseTimeStamp + countdownDuration
  const timeDiff = endTime - now

  if (timeDiff <= 0) {
    // 检查是否已经超时过，避免重复刷新
    return '已超时'
  }

  const minutes = Math.floor(timeDiff / (1000 * 60))
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000)

  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 获取送餐倒计时
const getDeliveryCountdown = (distributionTime) => {
  if (!distributionTime) return ''

  const now = new Date().getTime()
  const distributionTimeStamp = new Date(distributionTime).getTime()

  // 设置40分钟倒计时
  const countdownDuration = 40 * 60 * 1000 // 40分钟转换为毫秒
  const endTime = distributionTimeStamp + countdownDuration
  const timeDiff = endTime - now

  if (timeDiff <= 0) {
    // 检查是否已经超时过，避免重复刷新
    return '已超时'
  }

  const minutes = Math.floor(timeDiff / (1000 * 60))
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000)

  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 启动送餐倒计时
const startDeliveryCountdown = (orderId, distributionTime) => {
  console.log('启动送餐倒计时:', orderId, distributionTime);

  // 如果已经存在定时器，先停止
  if (deliveryCountdownTimers.value.has(orderId)) {
    const existingTimer = deliveryCountdownTimers.value.get(orderId)
    clearInterval(existingTimer)
    deliveryCountdownTimers.value.delete(orderId)
  }

  // 如果这个订单已经超时过，直接返回
  if (timeoutOrders.value.has(orderId)) {
    console.log('订单已经超时过，不再启动倒计时:', orderId);
    return;
  }

  const timer = setInterval(() => {
    // 再次检查是否已经超时过
    if (timeoutOrders.value.has(orderId)) {
      console.log('订单已超时，停止定时器:', orderId);
      clearInterval(timer)
      deliveryCountdownTimers.value.delete(orderId)
      return;
    }

    console.log('送餐倒计时更新:', orderId);

    // 检查是否超时
    const now = new Date().getTime()
    const distributionTimeStamp = new Date(distributionTime).getTime()
    const countdownDuration = 40 * 60 * 1000
    const endTime = distributionTimeStamp + countdownDuration
    const timeDiff = endTime - now

    if (timeDiff <= 0) {
      console.log('送餐倒计时超时，停止定时器:', orderId);

      // 标记为已超时
      timeoutOrders.value.add(orderId)

      // 立即停止这个定时器
      clearInterval(timer)
      deliveryCountdownTimers.value.delete(orderId)

      // 延迟刷新，确保定时器已经停止
      // setTimeout(() => {
      //   console.log('执行超时后的刷新:', orderId);
      //   fetchOrderList(true);
      // }, 200)

      return;
    }

    // 更新全局倒计时状态，强制所有组件重新渲染
    countdownState.value = Date.now()
  }, 1000)

  deliveryCountdownTimers.value.set(orderId, timer)
  console.log('送餐倒计时已启动，定时器ID:', timer);
}

// 同样修复取餐倒计时
const startCountdown = (orderId, responseTime) => {
  console.log('启动取餐倒计时:', orderId, responseTime);

  // 如果已经存在定时器，先停止
  if (countdownTimers.value.has(orderId)) {
    const existingTimer = countdownTimers.value.get(orderId)
    clearInterval(existingTimer)
    countdownTimers.value.delete(orderId)
  }

  // 如果这个订单已经超时过，直接返回
  if (timeoutOrders.value.has(orderId)) {
    console.log('订单已经超时过，不再启动倒计时:', orderId);
    return;
  }

  const timer = setInterval(() => {
    // 再次检查是否已经超时过
    if (timeoutOrders.value.has(orderId)) {
      console.log('订单已超时，停止定时器:', orderId);
      clearInterval(timer)
      countdownTimers.value.delete(orderId)
      return;
    }

    console.log('取餐倒计时更新:', orderId);

    // 检查是否超时
    const now = new Date().getTime()
    const responseTimeStamp = new Date(responseTime).getTime()
    const countdownDuration = 20 * 60 * 1000
    const endTime = responseTimeStamp + countdownDuration
    const timeDiff = endTime - now

    if (timeDiff <= 0) {
      console.log('取餐倒计时超时，停止定时器:', orderId);

      // 标记为已超时
      timeoutOrders.value.add(orderId)

      // 立即停止这个定时器
      clearInterval(timer)
      countdownTimers.value.delete(orderId)

      // 延迟刷新，确保定时器已经停止
      setTimeout(() => {
        console.log('执行超时后的刷新:', orderId);
        fetchOrderList(true);
      }, 200)

      return;
    }

    // 更新全局倒计时状态，强制所有组件重新渲染
    countdownState.value = Date.now()
  }, 1000)

  countdownTimers.value.set(orderId, timer)
  console.log('取餐倒计时已启动，定时器ID:', timer);
}

// 停止取餐倒计时
const stopCountdown = (orderId) => {
  if (countdownTimers.value.has(orderId)) {
    clearInterval(countdownTimers.value.get(orderId))
    countdownTimers.value.delete(orderId)
  }
}

// 停止送餐倒计时
const stopDeliveryCountdown = (orderId) => {
  if (deliveryCountdownTimers.value.has(orderId)) {
    clearInterval(deliveryCountdownTimers.value.get(orderId))
    deliveryCountdownTimers.value.delete(orderId)
  }
}

// 计算内容区高度
function calcContentHeight() {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  headerHeight.value = menuButtonInfo.bottom + 54
  // #endif
  contentHeight.value = systemInfo.windowHeight - headerHeight.value - (systemInfo.safeAreaInsets?.bottom || 0)
}

// 获取订单列表
const fetchOrderList = async (isRefresh = false) => {
  try {
    loading.value = true;

    if (isRefresh) {
      page.value = 1;
      orderList.value = [];
      // 重置超时标记
      timeoutOrders.value.clear()
    }

    // 根据当前标签类型选择不同的接口
    const currentTab = riderOrderTabs.value[activeIndex.value];
    const api = currentTab.type === 'available'
      ? 'shopping/riderOrders/findOrderList'  // 可接单列表
      : 'shopping/riderOrders/findReceivedOrderList';        // 骑手自己的订单列表

    const params = {
      pageNum: page.value,
      pageSize: 10,
    };

    // 如果是我的订单，添加状态筛选
    if (currentTab.type === 'my') {
      params.status = currentTab.status;
    }

    const res = await Fetch(api, {
      method: 'GET',
      data: params
    });

    if (res.data.code === 200) {
      console.log('接口返回数据:', res.data);

      const { rows = [], total = 0 } = res.data; // 设置默认值
      // 如果是空数组且是刷新操作，直接返回
      if (!rows || rows.length === 0) {
        orderList.value = isRefresh ? [] : orderList.value;
        hasMore.value = false;
        return;
      }

      // 处理订单数据
      const processedOrders = rows.map(order => {
        console.log('处理订单:', order);
        return {
          id: order.orderId,
          orderNo: order.orderNo,
          status: order.status,
          storeName: order.shopName,
          storeAddress: order.shopAddress,
          customerAddress: order.deliveryAddress,
          customerPhone: order.contactPhone,
          deliveryFeeStr: order.customerDistributionFeeStr || 0,
          items: order.orderGoods || [],
          createTime: order.createTime,
          payStatus: order.payStatus,
          customerDistributionFeeStr: order.customerDistributionFeeStr,
          distributionStatus: order.distributionStatus,
          totalAmountStr: order.totalAmountStr,
          actualPayAmountStr: order.actualPayAmountStr || order.needPayAmountStr,
          needPayAmountStr: order.needPayAmountStr,
          singleNumber: order.singleNumber, // 添加取餐码字段
          deliveryPhone: order.deliveryPhone,
          responseTime: order.responseTime, // 添加接单时间字段
          distributionTime: order.distributionTime, // 添加配送时间字段
          countdownUpdate: Date.now(), // 添加倒计时更新标识
          buyerNotes: order.buyerNotes, // 添加这一行
        };
      });

      orderList.value = isRefresh ? processedOrders : [...orderList.value, ...processedOrders];
      hasMore.value = orderList.value.length < total;
      if (hasMore.value) {
        page.value++;
      }

      console.log('处理后的订单列表:', processedOrders);

      // 为状态为2的订单启动取餐倒计时
      processedOrders.forEach(order => {
        console.log('检查订单状态:', order.id, order.status, order.responseTime);
        if (order.status === '2' && order.responseTime) {
          console.log('启动取餐倒计时:', order.id, order.responseTime);
          startCountdown(order.id, order.responseTime)
        }
        // 为状态为3的订单启动送餐倒计时
        if (order.status === '3' && order.distributionTime) {
          console.log('启动送餐倒计时:', order.id, order.distributionTime);
          startDeliveryCountdown(order.id, order.distributionTime)
        }
      })

    } else {
      uni.showToast({
        title: res.data.message || '获取订单列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    loadingMore.value = false;
    refreshing.value = false;
  }
}

// 切换标签
const handleTabChange = (index) => {
  if (activeIndex.value === index) return

  // 清理所有取餐倒计时
  countdownTimers.value.forEach((timer, orderId) => {
    clearInterval(timer)
  })
  countdownTimers.value.clear()

  // 清理所有送餐倒计时
  deliveryCountdownTimers.value.forEach((timer, orderId) => {
    clearInterval(timer)
  })
  deliveryCountdownTimers.value.clear()

  // 清理超时标记
  timeoutOrders.value.clear()

  activeIndex.value = index
  orderList.value = []
  page.value = 1
  hasMore.value = true
  fetchOrderList(true)
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    loadingMore.value = true
    fetchOrderList()
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  fetchOrderList(true);
}

// 上拉加载更多
const onLoadMore = () => {
  if (!hasMore.value || loading.value || loadingMore.value) return;

  loadingMore.value = true;
  fetchOrderList();
}

// 切换状态标签
const changeStatus = (status) => {
  if (currentStatus.value === status) return;

  currentStatus.value = status;
  fetchOrderList(true); // 切换状态时重新加载数据
}

// 接单
const takeOrder = async (order) => {
  console.log(order, 'order');

  uni.showModal({
    title: '接单确认',
    content: '确认接此订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await Fetch(`shopping/riderOrders/acceptOrder`, {
            method: 'get',
            data: {
              orderId: order.id,
            }
          });

          if (result.data.code === 200) {
            uni.showToast({
              title: '接单成功',
              icon: 'success'
            });
            fetchOrderList(true);
          } else {
            uni.showToast({
              title: result.data.msg || '接单失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('接单失败:', error);
          uni.showToast({
            title: '接单失败',
            icon: 'none'
          });
        }
      }
    }
  })
}

// 取消接单
const cancelOrder = async (order) => {
  uni.showModal({
    title: '取消接单',
    content: '确认取消接此订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await Fetch(`shopping/riderOrders/cancel/${order.orderId}`, {
            method: 'POST',
            data: {
              distributionStatus: '0'
            }
          });

          if (result.data.code === 200) {
            uni.showToast({
              title: '取消接单成功',
              icon: 'success'
            });
            fetchOrderList(true);
          } else {
            uni.showToast({
              title: result.data.message || '取消失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('取消接单失败:', error);
          uni.showToast({
            title: '取消接单失败',
            icon: 'none'
          });
        }
      }
    }
  })
}

// 开始配送（取货）
const startDelivery = async (order) => {
  currentOrder.value = order;
  currentOrderAction.value = 'pickup';
  photoList.value = [];
  remarks.value = '';
  showPhotoDialog.value = true;
}

// 确认送达
const confirmDelivery = async (order) => {
  currentOrder.value = order;
  currentOrderAction.value = 'delivery';
  photoList.value = [];
  remarks.value = '';
  showPhotoDialog.value = true;
}

// 提交凭证和备注
const submitPhotoAndRemarks = async () => {


  const photoUrls = photoList.value.map(photo => photo.serverUrl).filter(Boolean);

  try {
    const apiUrl = currentOrderAction.value === 'pickup'
      ? `shopping/riderOrders/takeMealOrder`
      : `shopping/riderOrders/completeOrder`;
    console.log(currentOrder, 'currentOrder,');

    const result = await Fetch(apiUrl, {
      method: 'POST',
      data: {
        imgUrl: photoUrls.join(','),
        remark: remarks.value,
        orderId: currentOrder.value.id
      }
    });

    if (result.data.code === 200) {
      showPhotoDialog.value = false;
      uni.showToast({
        title: currentOrderAction.value === 'pickup' ? '已开始配送' : '配送完成',
        icon: 'success'
      });
      fetchOrderList(true);
    } else {
      uni.showToast({
        title: result.data.msg || '操作失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('操作失败:', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
}

// 联系顾客
const contactCustomer = (order) => {
  console.log(order, 'order');
  if (order.deliveryPhone) {
    uni.showModal({
      title: '联系顾客',
      content: `将拨打电话：${order.deliveryPhone}`,
      success: (res) => {
        if (res.confirm) {
          uni.makePhoneCall({
            phoneNumber: order.deliveryPhone,
            fail: () => {
              uni.showToast({
                title: '拨打电话失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  } else {
    uni.showToast({
      title: '顾客联系方式不可用',
      icon: 'none'
    })
  }
}

// 拍照功能
const handleTakePhoto = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];

      // 显示上传中提示
      uni.showLoading({
        title: '上传中...'
      });

      try {
        // 上传图片到服务器
        const uploadRes = await uni.uploadFile({
          url: `${baseUrl}shopping/sysFile/upload`, // 替换为你的上传接口
          filePath: tempFilePath,
          name: 'file',
          header: {
            'accesstoken': loginStore.token
          }
        });

        const result = JSON.parse(uploadRes.data);
        console.log(result, 'result');

        if (result.code === 200) {
          photoList.value.push({
            localPath: tempFilePath,
            serverUrl: result.data.fileUrl
          });
        } else {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('上传失败:', error);
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  });
};

// 查看订单详情
const viewOrderDetail = (order) => {
  console.log(order,'order');

  uni.navigateTo({
    url: `/pages/RiderOrderDetail?orderId=${order.id}&activeIndex=${activeIndex.value}`,
  })
}

onMounted(() => {
  calcContentHeight()

})
onShow(() => {
  fetchOrderList(true)
})

// 组件卸载时清理所有倒计时和超时标记
onUnmounted(() => {
  countdownTimers.value.forEach((timer) => {
    clearInterval(timer)
  })
  countdownTimers.value.clear()

  deliveryCountdownTimers.value.forEach((timer) => {
    clearInterval(timer)
  })
  deliveryCountdownTimers.value.clear()

  timeoutOrders.value.clear()
})
</script>

<style lang="scss" scoped>
.rider-order {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;

  .rider-order-header {
    background: #FFFFFF;
    position: relative;
    margin-bottom: 20rpx;
    z-index: 2;

    .rider-order-header-bottom {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 96rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .rider-order-header-bottom-item {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .item-box {
          font-weight: bold;
          font-size: 28rpx;
          color: #191919;
          line-height: 40rpx;
          text-align: center;
          font-style: normal;
          text-transform: none;
          cursor: pointer;
        }

        .item-box-active {
          position: relative;

          &::after {
            content: '';
            display: block;
            width: 40rpx;
            height: 8rpx;
            background: #F9DC40;
            border-radius: 4rpx 4rpx 4rpx 4rpx;
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
          }
        }
      }
    }
  }

  .rider-order-content {
    overflow: auto;
    background: #F5F5F5;
    padding: 0 20rpx;
    box-sizing: border-box;

    .loading-container,
    .empty-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      background: #F5F5F5;
      border-radius: 20rpx;
      margin-top: 20rpx;
    }

    .loading {
      font-size: 28rpx;
      color: #999999;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }

    .order-item {
      background: #fff;
      margin: 16rpx 24rpx;
      border-radius: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
      overflow: hidden;
    }

    .order-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx;
      border-bottom: 1rpx solid #f5f5f5;
    }

    .shop-info {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .shop-avatar {
      width: 64rpx;
      height: 64rpx;
      border-radius: 12rpx;
      overflow: hidden;
      margin-right: 16rpx;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .shop-detail {
      .shop-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 4rpx;
      }

      .order-time {
        font-size: 24rpx;
        color: #999;
      }

      .pickup-countdown {
        display: flex;
        align-items: center;
        margin-top: 8rpx;

        .countdown-icon {
          font-size: 20rpx;
          margin-right: 8rpx;
          color: #ff6b35;
        }

        .countdown-text {
          font-size: 22rpx;
          color: #ff6b35;
          font-weight: 500;
        }
      }
    }

    .order-status {
      text-align: right;
    }

    .status-badge {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      font-weight: 500;
      margin-bottom: 8rpx;

      &.status-waiting {
        background: #fff3e0;
        color: #f57c00;
      }

      &.status-accepted {
        background: #e3f2fd;
        color: #1976d2;
      }

      &.status-delivering {
        background: #e8f5e8;
        color: #388e3c;
      }

      &.status-completed {
        background: #f3e5f5;
        color: #7b1fa2;
      }
    }

    .order-amount {
      font-size: 32rpx;
      font-weight: 600;
      color: #ff4757;
    }

    .order-detail {
      padding: 20rpx 24rpx;
    }

    .goods-summary {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 20rpx;

      .goods-count {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }

      .delivery-fee {
        font-size: 24rpx;
        color: #666;
      }

      .pickup-code {
        font-size: 24rpx;
        color: #191919;      /* 深色文字，更清晰 */
        background: #F9DC40; /* 高对比黄底 */
        padding: 4rpx 12rpx;
        border-radius: 8rpx;
      }
    }

    // 送餐倒计时样式
    .delivery-countdown {
      display: flex;
      align-items: center;
      margin: 16rpx 0;
      padding: 12rpx 16rpx;
      background: #fff3e0;
      border-radius: 12rpx;
      border-left: 4rpx solid #ff9800;

      .countdown-icon {
        font-size: 24rpx;
        margin-right: 12rpx;
        color: #ff9800;
      }

      .countdown-text {
        font-size: 24rpx;
        color: #e65100;
        font-weight: 600;
      }
    }

    .address-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .address-item {
        display: flex;
        align-items: center;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    .address-tag {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20rpx;
      font-weight: 600;
      color: #fff;
      margin-right: 16rpx;
      flex-shrink: 0;

      &.pickup-tag {
        background: #4477c8;
      }

      &.delivery-tag {
        background: #ff6b6b;
      }
    }

    .address-text {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
    }

    // 添加买家备注样式
    .buyer-notes {
      margin-top: 16rpx;
      padding: 16rpx;
      background: #fff9e6;
      border-radius: 12rpx;
      border-left: 4rpx solid #ffc107;

      .notes-label {
        font-size: 24rpx;
        color: #f57c00;
        font-weight: 600;
        margin-bottom: 8rpx;
      }

      .notes-content {
        font-size: 26rpx;
        color: #333;
        line-height: 1.5;
        word-wrap: break-word;
      }
    }

    .order-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 24rpx;
      background: #fafafa;
    }

    .contact-phone {
      display: flex;
      align-items: center;

      .phone-icon {
        margin-right: 8rpx;
      }

      .phone-number {
        font-size: 26rpx;
        color: #666;
      }
    }

    .action-btns {
      display: flex;
      gap: 16rpx;
    }

    .action-btn {
      padding: 16rpx 32rpx;
      border-radius: 28rpx;
      font-size: 28rpx;
      font-weight: 600;
      border: 1rpx solid transparent;
      min-width: 120rpx;
      line-height: 1;
      transition: all 0.2s ease;
      box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.06);
      transform: translateZ(0);

      &.primary-btn {
        background: linear-gradient(135deg, #FFD54F 0%, #FFA000 100%);
        color: #222; /* 黄底配深色字，更清晰 */
      }

      &.secondary-btn {
        background: #ffffff;
        color: #2B5AC8;
        border-color: #B7C6EC; /* 边框更明显 */
      }

      &:active {
        transform: translateY(1rpx);
        box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.08);
        filter: brightness(0.98);
      }

      &[disabled] {
        opacity: 0.6;
        pointer-events: none;
        box-shadow: none;
      }
    }
  }
}

.info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 10rpx;
  }

  .info-content {
    flex: 1;
    margin-left: 20rpx;

    .info-content-top {
      display: flex;
      justify-content: space-between;

      .store-name {
        font-size: 26rpx;
        color: #191919;
        line-height: 36rpx;
      }

      .store-name-tag {
        display: flex;
        align-items: center;
        color: #666;
        font-size: 24rpx;
      }
    }
  }
}

.page-line {
  width: 100%;
  height: 1rpx;
  background: #F5F5F5;
  margin: 10rpx 0;
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

/* 新增弹窗样式 */
.photo-dialog {
  width: 650rpx;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 30rpx;

  .dialog-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .photo-area {
    margin-bottom: 30rpx;

    .photo-list {
      display: flex;
      flex-wrap: wrap;

      .photo-item {
        width: 180rpx;
        height: 180rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;

        image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }
      }

      .photo-add {
        width: 180rpx;
        height: 180rpx;
        background-color: #f5f5f5;
        border-radius: 10rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #666;

        .iconfont {
          font-size: 48rpx;
          margin-bottom: 10rpx;
        }
      }
    }
  }

  .remarks-area {
    margin-bottom: 30rpx;

    .remarks-input {
      width: 100%;
      height: 150rpx;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      padding: 20rpx;
      box-sizing: border-box;
      font-size: 28rpx;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;

    button {
      width: 280rpx;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .btn-cancel {
      background-color: #E0E0E0;
      color: #191919;
    }

    .btn-submit {
      background-color: #F9DC40;
      color: #191919;
      font-weight: bold;
    }
  }
}
</style>
